<?php
namespace app\api\model;
use \think\Db;
use \think\Model;
class History extends Model
{
    /**
     * 历史记录
     */
    public function selHistoryById($member_id)
    {
        $field = [
            'h.history_id' => 'history_id',
            'h.add_time' => 'add_time',
            'm.movie_id' => 'movie_id',
            'm.movie_title' => 'movie_title',
            'm.face_pic' => 'face_pic'
        ];
        $list = Db::name("history")
            ->alias("h")
            ->field($field)
            ->join("__MOVIE__ m","h.movie_id = m.movie_id","left")
            ->where(['h.is_del'=>0,'h.member_id'=>$member_id])->order('h.add_time desc')->limit(100)->select();
        foreach ($list as $key => $value) {
            $list[$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        return $list;
    }

    /**
     * 添加记录
     */
    public function addHistory($data)
    {
        $history = $this->isHistory($data['member_id'],$data['movie_id']);
        if (!$history) {
            // 新增
            $data['add_time'] = time();
            $this->data($data);
            $result = $this->save();
            return $result;
        } else {
            // 更新
            $data['add_time'] = time();
            $result = $this->save($data,['history_id' => $history['history_id']]);
            return $result;
        }
    }

    /**
     * 记录状态
     */
    public function isHistory($member_id,$movie_id)
    {
        $result = Db::name("history")->where(['member_id'=>$member_id,'movie_id'=>$movie_id])->find();
        return $result;
    }

    /**
     * 删除记录
     */
    public function delHistory($history_id)
    {
        if ($history_id > 0) {
            $result = $this->save(['is_del' => 1],['history_id' => $history_id]);
            return $result;
        }
    }
}
